//
//  RouteViewController.m
//  SZBus
//
//  Created by Kengi Chan on 10/23/09.
//  Copyright 2009 IDMT. All rights reserved.
//

#import "SZBusAppDelegate.h"
#import "RouteViewController.h"

#import "Route.h"


@implementation RouteViewController

@synthesize table;
@synthesize search;

@synthesize filterRouteArray;

#pragma mark -
#pragma mark Search Customize methods

- (void)resetSearch{
	appDelegate = (SZBusAppDelegate *)[[UIApplication sharedApplication] delegate];
	self.filterRouteArray = [appDelegate.routeArray mutableCopy];
}

- (void)handleSearchForTerm:(NSString *)searchTerm{
//	NSMutableArray *
	appDelegate = (SZBusAppDelegate *)[[UIApplication sharedApplication] delegate];
	[self.filterRouteArray removeAllObjects];
	
	for (Route *route in appDelegate.routeArray) {
		if([route.routeName rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound )
		{	[self.filterRouteArray addObject:route];	}
//		NSComparisonResult result = [route.routeName compare:searchTerm 
//									 options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) 
//									 range:NSMakeRange(0, [searchTerm length])]; 
//		if (result == NSOrderedSame)
//		{
//			[self.filterRouteArray addObject:route];
//		}
	}
	[table reloadData];
}
/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/
#pragma mark -
#pragma mark UIViewController methods

- (void)viewDidLoad {
	[super viewDidLoad];
	[self resetSearch];
	[table reloadData];
	search.autocapitalizationType = UITextAutocapitalizationTypeNone;
	search.autocorrectionType = UITextAutocorrectionTypeNo;
	
	
	// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//	[self.table reloadData];
//}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.table = nil;
    self.search = nil;	
	self.filterRouteArray =nil;
}

- (void)dealloc {	
	[table release];
	[search release];	
	[filterRouteArray release];
    [super dealloc];
}


#pragma mark Table view methods
- (CGFloat)tableView:(UITableView *)tableView 
	heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 36.0f;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
	numberOfRowsInSection:(NSInteger)section 
{
	NSInteger routeCnt = [filterRouteArray count];
	//NSLog(@"103 %@" ,routeCnt);
    return routeCnt;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView 
	cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    
    static NSString *RouteCellIdentifier = @"RouteCell";    
    UITableViewCell *routeCell = [tableView dequeueReusableCellWithIdentifier:RouteCellIdentifier];
    if (routeCell == nil) {
		CGRect cellFrame = CGRectMake(0,0,300,65);
		routeCell = [[[UITableViewCell alloc] initWithFrame:cellFrame reuseIdentifier:RouteCellIdentifier] autorelease];
		
		CGRect nameLabelRect = CGRectMake(36, 7, 110, 20);
		UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
		nameLabel.font = [UIFont systemFontOfSize:14.0 ];
		nameLabel.tag = 1;
		[routeCell.contentView addSubview:nameLabel];
		[nameLabel release];
		
		CGRect titleLabelRect = CGRectMake(120, 8, 200, 20);
		UILabel *titleLabel = [[UILabel alloc] initWithFrame:titleLabelRect];
		titleLabel.font = [UIFont systemFontOfSize:11.0 ];
		titleLabel.tag = 2;
		[routeCell.contentView addSubview:titleLabel];
		[titleLabel release];
//#ifdef __IPHONE_3_0
//        routeCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RouteCellIdentifier] autorelease];
//#else
//		routeCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:RouteCellIdentifier] autorelease];
//#endif
    }
    UIImage *image = [UIImage imageNamed:@"imgroute.png"];	
    Route *route = [filterRouteArray objectAtIndex:indexPath.row];
	UILabel *nameLabel = (UILabel *)[routeCell.contentView viewWithTag: 1];
	nameLabel.text = route.routeName;
	UILabel *titleLabel = (UILabel *)[routeCell.contentView viewWithTag:2];
	titleLabel.text = route.routeTitle;
#ifdef __IPHONE_3_0	
	routeCell.imageView.image = image;
//	routeCell.textLabel.text = [[NSString alloc] initWithFormat:@"%@ (%@)", route.routeName,route.routeTitle];
//	routeCell.textLabel.font = [UIFont systemFontOfSize:18.0 ];
#else
	routeCell.image = image;
//	routeCell.text = [[NSString alloc] initWithFormat:@"%@ (%@)", route.routeName,route.routeTitle];
//	routeCell.font = [UIFont systemFontOfSize:18.0 ];
#endif	
    return routeCell;
}

#pragma mark -
#pragma mark Table View Delegate Methods

- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	[search resignFirstResponder];
	return indexPath;
}

- (void)tableView:(UITableView *)tableView 
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	//Route * route = [appDelegate.routeArray objectAtIndex:indexPath.row];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/
#pragma mark -
#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{	
	NSString *searchTerm = [searchBar text];
	NSLog(@"SearchButtonClicked %@",searchTerm);
	[self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar	
	textDidChange:(NSString *)searchTerm{	
	NSLog(@"textDidChange %@",searchTerm);
	if([searchTerm length] == 0){
		[self resetSearch];
		[table reloadData];
		return;
	}
	[self handleSearchForTerm:searchTerm];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
	NSLog(@"CancalButtonClicked");
	search.text = @"";
	[self resetSearch];
	[table reloadData];
	[searchBar resignFirstResponder];
}
@end

